package com.lzh.seatrend.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
//关于@EnableWebSecurity
/**
 * 如果用的是spring-boot-start-security，则不需要加
 */

/**
 * SpringSecurity提供了BCryptPasswordEncoder 密码编码工具,可以非常方便实现密码的加盐加密，相同明文加密出来的结果总是不同，
 * 这样就不需要额外保存
 */

/**
 * WebSecurityConfigurerAdapter web安全适配器，继承该类编写自己所特殊需要的配置
 */

/**
 * @author lzihao
 * @date 2021/7/19
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 1.配置认证信息
     * 2.userDetailsService 该类作用去获取用户信息，如从数据库中拿取用户信息
     * 当AuthenticationManager在认证用户身份的时候，就会从中获取用户身份，和从网页上拿到的
     * 用户身份做对比
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("javaboy")
            .roles("admin")
            .password("$2a$10$wLE/b0BxEQ6mzLldChDOMe/EBNMcXd.pZSQibHB84tQFFdw/Xgh.G")
            .and()
            .withUser("lzh")
            .roles("user")
            .password("$2a$10$wLE/b0BxEQ6mzLldChDOMe/EBNMcXd.pZSQibHB84tQFFdw/Xgh.G")
            ;
//        auth.userDetailsService(dbUserDetailService)
//        .passwordEncoder(passwordEncoder());
    }

     /**
     * 安全配置类，认证策略
      * 定义了哪些URL路径应该被保护
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置路径拦截
        http.authorizeRequests()
             .antMatchers().authenticated()
            .antMatchers("/**").hasRole("admin")
            .anyRequest().authenticated()
            .and().csrf().disable(); //添加 CSRF 支持，使用WebSecurityConfigurerAdapter时，默认启用
    }

//    /*登录配置*/
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.addFilterBefore()
//    }

//    装载BCrypt密码编码器
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    //TODO 加盐加密


}
